package com.qdxwx.web.controller.document;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.document.DocumentService;
import com.qdxwx.data.service.member.MemberRecordService;
import com.qdxwx.data.service.user.UserBuyService;
import com.qdxwx.data.service.user.UserCountService;
import com.qdxwx.data.service.user.UserDownloadService;
import com.qdxwx.models.document.DocumentDetail;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.member.MemberRecord;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import jakarta.servlet.http.HttpServletRequest;

/**
 * @author ZhiYong
 * @createTime 2021/4/13
 * @description
 */
@Controller
@RequestMapping("/document")
public class DocumentDownloadController extends BaseController {

    @Autowired
    private DocumentService documentService;
    @Autowired
    private UserCountService userCountService;
    @Autowired
    private MemberRecordService memberRecordService;
    @Autowired
    private UserDownloadService userDownloadService;
    @Autowired
    private UserBuyService userBuyService;

    /**
     * 下载
     */
    @PostMapping("/download.json")
    @ResponseBody
    public AjaxResult Download(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return AjaxResult.auth("此功能需要登录才能下载");
        }
        int id = TKConvert.toInteger(request.getParameter("id"));
        DocumentDetail document = documentService.get(id);
        if (document == null) {
            return AjaxResult.error("找不到指定资料");
        }
        if (document.getStatus() != 1) {
            return AjaxResult.error("该资料已经下架");
        }
        MemberRecord member = memberRecordService.getValidByUserId(user.getUserId(), 1);
        AjaxResult jsonResult = userCountService.checkDocumentLimit(user.getUserId(), member != null);
        if (jsonResult.getCode() > 0) {
            return AjaxResult.error(jsonResult.getMsg());
        }
        boolean isBuy = userBuyService.checkIsBuy(user.getUserId(), ModuleType.DOCUMENT.ordinal(),document.getId());
        if(document.getPrice() > 0 && !isBuy && member == null){
            return AjaxResult.error("您还没有购买该资料，无权下载");
        }
        documentService.updateDown(document.getId());
        userDownloadService.create(document, user);
        userCountService.updateDocumentDownCount(user.getUserId(), 1);
        return AjaxResult.success(document.getFileUrl(), 1);
    }
}
